<script lang="ts" setup>
import { ref, watch, onMounted } from 'vue'
import type { SearchClazzModel, ClazzModel, ClazzModelArray, EmpModelArray } from '@/api/model/model'
import { queryClazzList, updateClazz, getClazzById, addClazz, deleteClazzById } from '@/api/clazz/index'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
import { queryEmpLists } from '@/api/emp';

const searchForm = ref<SearchClazzModel>({ name: '', date: [], begin: '', end: '' })

const clear = () => {
    searchForm.value = { name: '', date: [], begin: '', end: '' }
}

// 把日期选择框中的2个日期赋值给begin和end，方便使用
watch(() => searchForm.value.date, (newValue, oldValue) => {
    // console.log(newValue);
    if (newValue && newValue.length > 0) {
        searchForm.value.begin = newValue[0];
        searchForm.value.end = newValue[1];
    } else {
        searchForm.value.begin = '';
        searchForm.value.end = '';
    }
});

onMounted(() => {
    query();
    queryEmp();
    console.log('object :>> ', EmpList.value);
});

const query = async () => {
    const res = await queryClazzList(searchForm.value.name, searchForm.value.begin, searchForm.value.end, currentPage.value, pageSize.value);
    clazzList.value = res.data.rows;
    total.value = res.data.total;
}


const queryEmp = async () => {
    const res = await queryEmpLists();
    EmpList.value = res.data;
}

const EmpList = ref<EmpModelArray>();

const clazzList = ref<ClazzModelArray>();
let currentPage = ref(1)
const pageSize = ref(5);
const total = ref(0)

const handleSizeChange = () => {
    currentPage = ref<number>(1);
    query();
}

const handleCurrentChange = () => {
    query()
}


const openAddDialog = () => {
    dialogFormVisible.value = true;
    dialogTitle.value = "新增班级";
}

// dialog弹框
const formLabelWidth = "80px";
const dialogFormVisible = ref<boolean>(false)
const dialogTitle = ref<string>('')
const insertOrUpdateForm = ref<ClazzModel>({
    id: '',
    name: '',
    room: '',
    beginDate: '',
    endDate: '',
    subject: '',
    status: '',
    masterId: '',
    masterName: '',
    updateTime: ''
});

const insertOrUpdate = (formEL: FormInstance | undefined) => {
    if (!formEL) {
        return;
    }
    // 先校验表单的格式
    formEL.validate(async (valid) => {
        if (valid) {
            // 校验通过
            let res = null;
            let insertFlag = null;
            if (insertOrUpdateForm.value.id) {//修改
                insertFlag = false;
                res = await updateClazz(insertOrUpdateForm.value);
            } else {// 新增
                insertFlag = true;
                res = await addClazz(insertOrUpdateForm.value);
            }
            if (!res.code) {
                ElMessage.error(res.msg);
            } else {
                // 隐藏dialog
                dialogFormVisible.value = false;
                // 清空dialog，通过dialog的回调统一处理
                ElMessage({ type: 'success', message: insertFlag ? '添加成功' : '修改成功', })
                query();
            }
        }
    });

}
const dialogFromRef = ref<FormInstance>();
// 表单校验
const rules = ref<FormRules<ClazzModel>>({
    name: [
        { required: true, message: '班级名称不能为空', trigger: 'blur' },
    ],
    beginDate: [
        { required: true, message: '开课时间不能为空', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('开课时间不能为空'));
                }
                // 转换为日期对象进行比较  
                const inputDate = new Date(value);
                const now = new Date(getCurrentDate());
                if (inputDate > now) {
                    callback(new Error('开课时间不能晚于当前时间'));
                } else {
                    callback();
                }
            }, trigger: 'blur'
        },
    ],
    endDate: [
        { required: true, message: '结课时间不能为空', trigger: 'blur' },

    ],
    subject: [
        { required: true, message: '学科不能为空', trigger: 'blur' },

    ],
})


// 更新
const handleEdit = async (idx: number, row: ClazzModel) => {
    if (!row.id) {
        return;
    }
    // 展示弹框
    dialogFormVisible.value = true;
    dialogTitle.value = "修改班级";
    // 回显查询，参数是id
    const res = await getClazzById(row.id);
    insertOrUpdateForm.value = res.data;
}

//删除
const handleDelete = (idx: number, row: ClazzModel) => {
    ElMessageBox.confirm('您确认删除此数据吗?', '确认删除', { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning', })
        .then(async () => {
            // 发删除请求
            const res = await deleteClazzById('' + row.id);
            if (!res.code) {
                ElMessage({ type: 'error', message: res.msg, })
            } else {
                ElMessage({ type: 'success', message: '删除成功' })
                // 刷新页面
                query();
            }
        }).catch(() => {
            ElMessage({ type: 'info', message: '取消删除' })
        })
}


// dialog关闭的时候自动回调
function dialogClose() {
    if (!dialogFromRef || !dialogFromRef.value) {
        return;
    }
    insertOrUpdateForm.value =
    {
        id: '',
        name: '',
        room: '',
        beginDate: '',
        endDate: '',
        subject: '',
        status: '',
        masterId: '',
        masterName: '',
        updateTime: ''
    }
    // 重置form校验规则
    dialogFromRef.value.resetFields();
}
const subjectList = [{ id: 1, name: 'java' }, { id: 2, name: '前端' }, { id: 3, name: '大数据' }, { id: 4, name: 'Python' }, { id: 5, name: 'Go' }, { id: 6, name: '嵌入式' }]

</script>


<template>
    <span class="title">班级管理 </span>
    <!----------------------------------搜索框-------------------------------------->
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="班级名称">
            <el-input v-model="searchForm.name" placeholder="请输入班级姓名" style="width:200px" clearable />
        </el-form-item>
        <el-form-item label="结课时间">
            <el-date-picker v-model="searchForm.date" value-format="YYYY-MM-DD" type="daterange" range-separator="至"
                start-placeholder="开始时间" end-placeholder="结束时间" />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="query">查询</el-button>
            <el-button type="info" @click="clear">清空</el-button>
        </el-form-item>
    </el-form>

    <el-button type="success" @click="openAddDialog">+ 新增班级</el-button>

    <!-----------------------页面主体的数据列表-------------------------------->
    <el-table :data="clazzList" border style="width: 100%; margin-top:10px">
        <el-table-column type="index" label="序号" width="70" />
        <el-table-column prop="name" label="班级名称" width="150" align="center" />
        <el-table-column prop="room" label="班级教室" width="100" align="center" />
        <el-table-column prop="masterName" label="班主任" width="180" align="center" />
        <el-table-column prop="beginDate" label="开课时间" width="180" align="center" />
        <el-table-column prop="endDate" label="结课时间" width="180" align="center" />
        <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
                <el-tag type="primary">{{ scope.row.status }}</el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="最后修改时间" width="180" align="center" />
        <el-table-column label="操作" align="center">
            <template #default="scope">
                <el-button size="small" type="primary" @click="handleEdit(scope.$index, scope.row)">
                    编辑
                </el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">
                    删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>
    <!----------------------------------分页组件---------------------------------------->
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" style="margin-top:10px" />

    <!----------------------------------dialog弹框-------------------------------------->
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="600" @close="dialogClose">
        <el-form :model="insertOrUpdateForm" ref="dialogFromRef" :rules="rules">
            <el-row>
                <el-col>
                    <el-form-item label="班级名称" :label-width="formLabelWidth" prop="name" required>
                        <el-input v-model="insertOrUpdateForm.name" autocomplete="off" placeholder="请输入班级名称"
                            clearable />
                    </el-form-item>
                </el-col>

            </el-row>

            <el-row>
                <el-col>
                    <el-form-item label="班级教室" :label-width="formLabelWidth" prop="room">
                        <el-input v-model="insertOrUpdateForm.room" autocomplete="off" placeholder="请输入班级教室"
                            clearable />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col>
                    <el-form-item label="开课时间" :label-width="formLabelWidth" style="width:100%" required>
                        <el-date-picker style="width:100%" v-model="insertOrUpdateForm.beginDate" type="date"
                            value-format="YYYY-MM-DD" placeholder="选择开课时间" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col>
                    <el-form-item label="结课时间" :label-width="formLabelWidth" style="width:100%" required>
                        <el-date-picker style="width:100%" v-model="insertOrUpdateForm.endDate" type="date"
                            value-format="YYYY-MM-DD" placeholder="选择结课时间" />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col>
                    <el-form-item label="班主任" :label-width="formLabelWidth">
                        <el-select v-model="insertOrUpdateForm.masterId" placeholder="请选择班主任" style="width: 100%">
                            <el-option :label="emp.name" :value="emp.id" v-for="(emp, index) in EmpList"
                                :key="emp.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col>
                    <el-form-item label="学科" :label-width="formLabelWidth" required #default="scope">
                        <el-select v-model="insertOrUpdateForm.subject" placeholder="请选择" clearable style="width: 100%">
                            <el-option :label="subject.name" :value="subject.id" v-for="(subject, index) in subjectList"
                                :key="subject.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="insertOrUpdate(dialogFromRef)">保存</el-button>
            </div>
        </template>
    </el-dialog>


</template>
<style scope>
.title {
    font-size: 20px;
    font-weight: 600;
}

.demo-form-inline {
    margin-top: 10px
}
</style>